from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import sys
from pathlib import Path
from werkzeug.utils import secure_filename
# 导入并注册路由
from routes import register_routes
from TestMyDeepSeekDemo1 import process_test_case_generation
# 获取当前文件的目录
current_dir = Path(__file__).parent

# 添加项目根目录到 Python 路径
project_root = current_dir.parent
sys.path.append(str(project_root))



app = Flask(__name__)
# 允许跨域请求
CORS(app, resources={r"/*": {"origins": "*"}})

# 创建上传文件夹
UPLOAD_FOLDER = current_dir / 'uploads'
UPLOAD_FOLDER.mkdir(exist_ok=True)
@app.route('/generate-test-cases', methods=['POST'])
def handle_generate_test_cases():
    try:
        if 'file' not in request.files:
            return jsonify({'error': 'No file uploaded'}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No file selected'}), 400

        # 创建上传文件夹（如果不存在）
        upload_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
        if not os.path.exists(upload_folder):
            os.makedirs(upload_folder)
        
        # 保存上传的文件
        filename = secure_filename(file.filename)
        file_path = os.path.join(upload_folder, filename)
        file.save(file_path)
        
        # 设置CSV输出路径
        csv_filename = f"test_cases_{os.path.splitext(filename)[0]}.csv"
        csv_path = os.path.join(upload_folder, csv_filename)
        
        # 导入TestMyDeepSeekDemo模块
        sys.path.append(os.path.dirname(os.path.abspath(__file__)))
        # 调用测试用例生成函数
        success, result = process_test_case_generation(file_path, csv_path)
        
        if success:
            # 检查结果是否为有效测试用例列表
            if not isinstance(result, list):
                return jsonify({'error': '生成的测试用例数据格式错误'}), 500
            
            # 读取生成的CSV文件
            with open(csv_path, 'r', encoding='utf-8') as f:
                csv_content = f.read()
            
            return jsonify({'test_cases': result}), 200
        else:
            return jsonify({'error': result}), 500
        
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"[ERROR][{e.__class__.__name__}] {str(e)}\nStacktrace:\n{error_details}")
        return jsonify({
            'error': '内部服务器错误',
            'code': 500,
            'type': e.__class__.__name__,
            'detail': str(e)
        }), 500


@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'ok'}), 200

# 获取当前文件的目录
current_dir = Path(__file__).parent

# 添加项目根目录到 Python 路径
project_root = current_dir.parent
sys.path.append(str(project_root))

# 创建Flask应用
app = Flask(__name__)

# 允许跨域请求
CORS(app, resources={r"/*": {"origins": "*"}})

# 创建上传文件夹
UPLOAD_FOLDER = current_dir / 'uploads'
UPLOAD_FOLDER.mkdir(exist_ok=True)


register_routes(app)

# 添加一个说明性的注释，明确这是应用的入口点
"""
应用入口点
运行方式：
1. 直接运行此文件: python DSFlask.py
2. 使用Flask命令: flask --app DSFlask run
3. 使用Gunicorn (生产环境): gunicorn DSFlask:app

前端页面将通过此Flask应用上传文件并获取生成的测试用例。
TestMyDeepSeekDemo.py 将作为模块被导入，不需要单独运行。
"""
if __name__ == '__main__':
    print("启动测试平台服务...")
    print("访问 http://localhost:5000 使用测试平台")
    app.run(host='0.0.0.0', port=5000, debug=True)